package com.longge.websocket.util;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;

import org.springframework.web.socket.WebSocketSession;

import com.longge.websocket.config.MySession2;
import com.sun.jersey.client.impl.CopyOnWriteHashMap;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MySessionUtils {
	private static final Map<String, MySession2> sessionCache = new CopyOnWriteHashMap<>();

	public static void addSession(@NonNull String uid, WebSocketSession session) {
		if(sessionCache.containsKey(uid)) {
			log.info("User:{} have other session, kill other");
			try {
				sessionCache.get(uid).getSession().close();
			} catch (IOException e) {
				log.error("close other session error", e);
			}
		}
		sessionCache.put(uid, MySession2.builder().session(session).userId(uid).build());
	}

	public static String removeSession(WebSocketSession session) {
		Optional<Entry<String, MySession2>> op = sessionCache.entrySet().stream().filter(entry -> {
			return entry.getValue().getSession().equals(session);
		}).findFirst();
		String user = null;
		if(op.isPresent()) {
			user = op.get().getKey();
			sessionCache.remove(user);
		}
		return user;
	}

	public static Optional<WebSocketSession> getSession(@NonNull String uid) {
		MySession2 session = sessionCache.get(uid);
		if (null == session) {
			return Optional.empty();
		}
		return Optional.of(session.getSession());
	}

	public static Collection<MySession2> getAllSession() {
		return sessionCache.values();
	}
	
	public static Map<String, MySession2> getCacheSession() {
		return sessionCache;
	}
	
	public static Optional<String> getUserIdBySession(@NonNull WebSocketSession session) {
		Optional<MySession2> op = sessionCache.values().parallelStream().filter(item -> {
			return item.getSession().equals(session);
		}).findFirst();
		if(op.isPresent()) {
			return Optional.of(op.get().getUserId());
		}
		return Optional.empty(); 
	}
}
